var arr = [{
    id: 1,
    name: "yuan0",
    pid: 0
},
{
    id: 2,
    name: "yuan2",
    pid: 1
},
{
    id: 3,
    name: "yuan3",
    pid: 1
},
{
    id: 4,
    name: "yuan4",
    pid: 2
},
{
    id: 5,
    name: "yuan5",
    pid: 3
}, {
    id: 6,
    name: "yuan6",
    pid: 2
}]
function arrToTree(arr = []) {
    for (let i = 0; i < arr.length; i++) {
        let parent= findParent(arr,arr[i].pid)
        if (parent) {
            if (parent.children) {
                parent.children.push(arr[i]);
            } else {
                parent.children = [arr[i]];
            }
            arr.splice(i, 1);
            i--;
        }
    }
    return arr;
}
function findParent(arr = [], pid) {
    for(let i=0;i<arr.length;i++){
        if (arr[i].id == pid) {
            return arr[i];
        } else {
            if(arr[i].children){
                var res=findParent(arr[i].children,pid)
                if(res){
                    return res;
                }               
            }           
        }
    }
    return null;
}
console.log(arrToTree(arr));